// pages/sphygmomanometer/syncHistoryData/index.js
const {
  QNMPPlugin,
  QNConsts,
  QNBleProtocols
} = requirePlugin('QNBleApi');
const {
  SphygmomanometerV2Protocol
} = QNBleProtocols;
const {
  QNBleAction
} = QNConsts;
console.info('QNBleAction', QNBleAction);
/**
 * 微信的本地日志功能，需要用户手动反馈才能拿到日志文件。
 */
const logger = () => {
  const wxlogger =
    wx.getLogManager &&
    wx.getLogManager({
      level: 0,
    });
  const log = (...params) => {
    console.log(...params);
    wxlogger && wxlogger.log(...params);
  };
  return {
    log,
  };
};
// wxb0989a4bbce13d87为测试用appid, 记得切换为客户自己的
const APPID = 'wxb0989a4bbce13d87';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    deviceId: '',
    wifiName: '',
    wifiPassword: '',
    wifiList: [],
    hideWifiList: true,
    isScaningWifi: false,
    sceneData: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.bleApi = new QNMPPlugin({
      appId: APPID, // 必须, 客户小程序的appid, 需要配置才能使用，
      logger: logger(), // 非必须，日志功能，最好有，方便排查问题，可以替换为客户自己的
      protocols: [SphygmomanometerV2Protocol],
    });

    this.bleApi.onError = (err) => {
      console.error('捕捉到错误', err.detail);
    };

    // 初始化回调
    this.bleApi.onReady = ({
      bleEnableState, //表示当前蓝牙是否为开启状态
    }) => {
      if (bleEnableState) {
        this.bleApi.startBleDeviceDiscovery();
      } else {
        console.log('蓝牙状态为关闭');
      }
    };
    // 设置蓝牙监听事件
    this.bleApi.setBleEventListener(this.bleEventListener());
    // 初始化
    this.bleApi.init();
  },

  deviceEventListener() {
    /**
     * 获取设备信息
     * @param {object} deviceInfo
     */
    const onGetDeviceInfo = (deviceInfo) => {
      console.info('设备信息', deviceInfo);
      const {
        deviceId,
      } = deviceInfo;
      this.setData({
        deviceId,
        sceneData: 1
      })
    };

    const onSetWifiSuccess = () => {
      wx.hideLoading({
        success: () => {
          wx.showModal({
            title: "提示",
            content: '配网成功',
            showCancel: false,
            success() {
              wx.navigateBack()
            }
          })
        },
      })
    };

    const onSetWifiFail = () => {
      wx.hideLoading({
        success: () => {
          wx.showModal({
            title: "提示",
            content: '配网失败',
            cancelText: '返回首页',
            confirmText: '重新配网',
            success: async () => {
              await this.bleApi.stop();
              this.setData({
                sceneData: 0
              })
              setTimeout(() => {
                this.bleApi.startBleDeviceDiscovery();
              }, 500)
            },
            fail() {
              this.setData({
                wifiName: '',
                wifiPassword: '',
                wifiList: [],
              })
              wx.navigateBack({
                delta: 0,
              })
            }
          })
        },
      })
    };

    const onGetWifiInfo = ({
      ssid
    }) => {
      console.info('info', ssid);
      const {
        wifiList
      } = this.data
      wifiList.push({
        ssid
      })
      this.setData({
        wifiList
      })
    };

    const onScanWifiFinished = () => {
      this.setData({
        isScaningWifi: false
      })
    };

    return {
      onGetDeviceInfo,
      onSetWifiSuccess,
      onSetWifiFail,
      onGetWifiInfo,
      onScanWifiFinished,
    };
  },

  /**
   * 设置蓝牙提示
   * @param {string} bleState
   * 蓝牙提示信息
   */
  updateState(bleState) {
    this.setData({
      bleState,
    });
  },

  // 蓝牙相关事件回调
  bleEventListener() {
    /**
     * 监听扫描到设备的回调
     */
    const onBleDeviceFound = async (device) => {
      console.info('device', device);
      this.deviceHandler = await this.bleApi.createBleConnection(
        device,
        this.deviceEventListener(), {
          action: QNBleAction.SET_WIFI,
        },
      );
      this.setData({
        isScaningWifi: true
      })
    };

    /**
     * 监听蓝牙断开连接的回调
     */
    const onDisconnected = (device) => {
      this.updateState('设备连接已断开');
      this.setData({
        connected: false,
        state: 'paused',
        connecting: false,
        device,
      });
      this.connecting = false;
      this.connected = false;
      console.log('设备连接已断开', device);
    };

    /**
     * 监听蓝牙状态发生变化回调，连接成功或断开连接都会出触发
     */
    const onBluetoothEnableChange = ({
      available
    }) => {
      if (available) {
        this.updateState('蓝牙可用，空闲');
        this.bleApi.startBleDeviceDiscovery();
      } else {
        this.updateState('蓝牙不可用');
      }
      this.setData({
        available,
      });
    };

    /**
     * 	监听设备连接成功回调
     */
    const onConnected = (device) => {
      this.updateState('已连接');
      console.log('设备已连接', device);
      this.connecting = false;
      this.setData({
        connected: true,
        state: 'running',
        device,
      });
    };

    /**
     * 监听停止扫描的回调
     */
    const onStopDiscoveryDevice = () => {
      this.updateState('已停止扫描');
      this.setData({
        discovering: false,
      });
    };

    /**
     * 监听开始扫描设备的回调
     */
    const onStartDiscoveryDevice = () => {
      this.updateState('开始扫描');
      this.setData({
        devices: [],
        discovering: true,
      });
    };

    return {
      onBleDeviceFound,
      onDisconnected,
      onBluetoothEnableChange,
      onConnected,
      onStopDiscoveryDevice,
      onStartDiscoveryDevice,
    };
  },

  /**
   * 停止蓝牙活动
   */
  async stopBle() {
    await this.bleApi.stop();
    await this.bleApi.releaseBleSource();
  },

  handleSelectWifiName(e) {
    const {
      ssid
    } = e.currentTarget.dataset
    this.setData({
      wifiName: ssid,
      hideWifiList: true
    })
  },

  doScanWifi() {
    this.bleApi.callProtocolMethodAsync(this.data.deviceId, 'doScanWifi', [])
  },

  doSetWifi() {
    const data = {
      wifiSsid: this.data.wifiName,
      wifiPwd: this.data.wifiPassword,
      dataServerUrl: 'https://wsp-lite.yolanda.hk:443/yolanda/bps?code=',
      encryptKey: 'yolandakitnewhdr',
    }
    this.bleApi.callProtocolMethodAsync(this.data.deviceId, 'doSetWifi', [data])
    wx.showLoading({
      title: '开始配网',
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.stopBle();
  },

  handleChangeShowSelectWifi() {
    this.setData({
      hideWifiList: !this.data.hideWifiList
    })
  }
});